//
//  SHPOriginalView.swift
//  weibo
//
//  Created by songhuipan on 16/4/21.
//  Copyright © 2016年 songhuipan. All rights reserved.
//

import UIKit
import SnapKit

class SHPOriginalView: UIView {
    
    var originalViewBottomConstraint: Constraint?
    
    var status:SHPStatus?{
        didSet {
            // 设置微博头像
            headerImageView .sd_setImageWithURL(NSURL(string: (status?.user?.profile_image_url) ?? ""), placeholderImage: UIImage(named: "avatar_default_big"))
            // 设置微博用户姓名
            nameLabel.text = status?.user?.screen_name
            // 设置微博等级
            mbrankImageView.image = getMbrankImage((status?.user?.mbrank) ?? 0)
            // 设置微博认证
            verified_typeImageView.image = getverified_typeImage((status?.user?.verified_type)!)
            // 设置微博发布时间
            timeLabel.text = getCreatedTime((status?.created_at)!)
            // 设置微博发布来源显示
            sourceLabel.attributedText = getSourceString(status?.source)
            // 设置微博正文内容
            contentLabel.attributedText = setWeiboAttr(status?.text ?? "")
//            print(contentLabel.attributedText)
            originalViewBottomConstraint?.uninstall()
            
            if (status?.pic_urls?.count) != 0 && status?.pic_urls != nil {
                
                pictureCollectionView.hidden = false
                pictureCollectionView.pic_urls = status?.pic_urls
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(pictureCollectionView.snp_bottom).offset(10).constraint
                })
            }else {
                pictureCollectionView.hidden = true
                
                self.snp_makeConstraints(closure: { (make) -> Void in
                    self.originalViewBottomConstraint = make.bottom.equalTo(contentLabel.snp_bottom).offset(10).constraint
                })
            }
        }
    }
    // MARK:处理图文混排的问题
    func setWeiboAttr(text:String)->NSMutableAttributedString{
        
        let attr = NSMutableAttributedString(string: text)
        // 创建一个数组，存贮使用正则表达式搜索出来的结果
        var matchResultArray:[SHPMatchResult] = [SHPMatchResult]()
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, result, range, _) -> Void in
            
            let match = SHPMatchResult(string: (result.memory as! String), range: range.memory)
            
            matchResultArray.append(match)
        }
        for match in matchResultArray.reverse() {
            
            let emoticonModel = SHPEmoticonTool.sharedTools.getEmoticonModel(match.string)
            
            guard let emoticon = emoticonModel else {
                return NSMutableAttributedString(string: "")
            }
//            print(emoticon)
            // 根据名字拼接路径时，如果不设置??""会出现所发送的表情按钮图片不能显示
            // 下面的path和png都是可选项，如果不解包，会造成拼接的path不正确，不能正确的从本地得到图片
//            print("\(emoticon.path)--path")
//            print("\(emoticon.png)--png")
//            print("\(emoticon.png)\(emoticon.png)")
            let path = "\(emoticon.path ?? "")\(emoticon.png ?? "")"
            
            let image = UIImage(named: path, inBundle: SHPEmoticonTool.sharedTools.emoticonBundle, compatibleWithTraitCollection: nil)
            let attach = NSTextAttachment()
            attach.image = image
            let height = UIFont.systemFontOfSize(14).lineHeight
            attach.bounds = CGRectMake(0, -4, height, height)
            
            // 初始化一个不可变富文本
            let att = NSAttributedString(attachment: attach)
            
            // 替换富文本
            attr.replaceCharactersInRange(match.range, withAttributedString: att)
//            print(attr)
        }
        return attr
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:懒加载头像
    private lazy var headerImageView:UIImageView = UIImageView(image: UIImage(named: "avatar_default_big"))
    
    // MARK:懒加载用户昵称
    private lazy var nameLabel :UILabel = UILabel(textColor: UIColor.darkGrayColor(), textFont: 14)
    // MARK:懒加载会员等级
    private lazy var mbrankImageView:UIImageView = UIImageView(image: UIImage(named: "common_icon_membership"))
    // MARK:懒加载时间
    private lazy var timeLabel :UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    // MARK:懒加载来源
    private lazy var sourceLabel:UILabel = UILabel(textColor: ThemeColor, textFont: 10)
    // MARK:懒加载认证类型
    private lazy var verified_typeImageView = UIImageView(image: UIImage(named: "avatar_vip"))
    // MARK:微博正文内容的懒加载
    private lazy var contentLabel :UILabel = {
        let contentLabel = UILabel(textColor: UIColor.blackColor(), textFont: 14)
        contentLabel.numberOfLines = 0
        return contentLabel
    }()
    // MARK:懒加载微博正文图片
    private lazy var pictureCollectionView:SHPPictureView = {
        let pictureView:SHPPictureView = SHPPictureView()
        return pictureView
    }()
}
extension SHPOriginalView {
    // MARK:设置微博发布时间的方法
    private func getCreatedTime(time:String)->String {
        // 根据字符串形式获得时间
        let df = NSDateFormatter()
        df.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        let weiboDate = df.dateFromString(time)!
        let isThisYear = isCurrentYear(weiboDate)
        
        if isThisYear {
            let calendar = NSCalendar.currentCalendar()
            if calendar.isDateInToday(weiboDate) {
                // 获得当前时间距微博发布时间有多少秒
                let s = NSDate().timeIntervalSinceDate(weiboDate)
                if s < 60 {
                    return "刚刚"
                }else if s>60 && s<3600 {
                    return "\(Int(s/60))分钟前"
                }else {
                    return "\(Int(s/3600))小时前"
                }
                
            }else if calendar.isDateInYesterday(weiboDate){
                df.dateFormat = "昨天 HH:mm"
                return df.stringFromDate(weiboDate)
            }else {
                df.dateFormat = "MM月dd日 HH:mm"
                return df.stringFromDate(weiboDate)
            }
        }else {
            df.dateFormat = "yyyy年MM月dd日 HH:mm"
            return df.stringFromDate(weiboDate)
        }
    }
    // MARK:判断是否是今年的方法
    private func isCurrentYear(weiboDate:NSDate)->Bool {
        // 设置时间字符串格式
        let df = NSDateFormatter()
        df.dateFormat = "yyyy"
        // 设置local
        df.locale = NSLocale(localeIdentifier: "en_US")
        // 获得微博时间的格式字符串
        let weiboTimeString = df.stringFromDate(weiboDate)
        // 获得当前时间的格式字符串
        let currentTimeString = df.stringFromDate(NSDate())
        // 比较是否是今年
        if weiboTimeString == currentTimeString {
            return true
        }else {
            return false
        }
    }
    // MARK:通过富文本设置来源字符串
    func getSourceString(source:String?)->NSMutableAttributedString {
        guard let sourceString = source where sourceString.containsString("\">") else{
            return NSMutableAttributedString(string: "")
        }
        let startRange = sourceString.rangeOfString("\">")
        let endRange = sourceString.rangeOfString("</a")
        let resultString = sourceString.substringWithRange((startRange?.endIndex)!..<(endRange?.startIndex)!)
        let name = "来自\(resultString)"
        let attr = NSMutableAttributedString(string: name)
        
        let range = (name as NSString).rangeOfString("来自")
        attr.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: range)
        return attr
        
    }
    // MARK:根据认证类型的不同返回不同的图片
    func getverified_typeImage(verified_type:Int)->UIImage {
        switch verified_type {
        case 0 :
            return UIImage(named: "avatar_vip")!
        case 2,3,5 :
            return UIImage(named: "avatar_enterprise_vip")!
        case 220 :
            return UIImage(named: "avatar_grassroot")!
        default:
            return UIImage(named: "avatar_vgirl")!
            
        }
    }
    // MARK:根据等级返回对应的图片
    func getMbrankImage (mbrank:Int)->UIImage {
        
        if mbrank <= 0 {
            
            return UIImage(named: "avatar_vip")!
        }else {
            
            return UIImage(named: "common_icon_membership_level\(mbrank)")!
        }
    }
    // MARK:设置原创微博界面
    func setupUI () {
        backgroundColor = UIColor.whiteColor()
        
        addSubview(headerImageView)
        headerImageView.snp_makeConstraints { (make) -> Void in
            make.top.leading.equalTo(self).offset(10)
            make.size.equalTo(CGSizeMake(35, 35))
        }
        addSubview(nameLabel)
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headerImageView)
            make.leading.equalTo(headerImageView.snp_trailing).offset(10)
            
        }
        addSubview(mbrankImageView)
        mbrankImageView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(nameLabel)
            make.leading.equalTo(nameLabel.snp_trailing).offset(10)
        }
        addSubview(timeLabel)
        timeLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(headerImageView)
            make.leading.equalTo(headerImageView.snp_trailing).offset(10)
        }
        addSubview(sourceLabel)
        sourceLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(timeLabel)
            make.leading.equalTo(timeLabel.snp_trailing).offset(10)
        }
        addSubview(verified_typeImageView)
        verified_typeImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(headerImageView.snp_trailing)
            make.centerY.equalTo(headerImageView.snp_bottom)
        }
        addSubview(contentLabel)
        contentLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(headerImageView.snp_bottom).offset(10)
            make.leading.equalTo(headerImageView)
            make.width.equalTo(kScreenWidth-20)
            
        }
        addSubview(pictureCollectionView)
        pictureCollectionView.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self).offset(10)
            make.top.equalTo(contentLabel.snp_bottom).offset(10)
            
        }
        
        self.snp_makeConstraints { (make) -> Void in
            self.originalViewBottomConstraint = make.bottom.equalTo(pictureCollectionView.snp_bottom).constraint
        }
    }
}


















